package com.wenzhoujie;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.wenzhoujie.adapter.PayorderCodesAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.PaymentType;
import com.wenzhoujie.constant.Constant.PaymentTypeString;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.alipay.easy.PayResult;
import com.wenzhoujie.library.alipay.easy.SDAlipayer.SDAlipayerListener;
import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.MalipayConfigModel;
import com.wenzhoujie.model.MalipayModel;
import com.wenzhoujie.model.Pay_orderActCouponlistModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.WxAppModel;
import com.wenzhoujie.model.WxConfigModel;
import com.wenzhoujie.model.act.Pay_orderActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.wxpay.WXPayer;

public class PayActivity extends BaseActivity implements OnClickListener
{
	/** 订单id (String) */
	public static final String EXTRA_ORDER_ID = "extra_order_id";

	@ViewInject(id = R.id.act_pay_tv_order_sn)
	private TextView mTvOrderSn = null;

	@ViewInject(id = R.id.act_pay_tv_pay_info)
	private TextView mTvPayInfo = null;

	@ViewInject(id = R.id.act_pay_btn_pay)
	private Button mBtnPay = null;

	@ViewInject(id = R.id.act_pay_ll_scan_code)
	private LinearLayout mLlScanCodes = null;

	private String mStrOrderId = null;

	private Pay_orderActModel mPay_orderActModel = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_pay);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		initIntentData();
		initTitle();
		registeClick();
		requestPayOrder();
	}

	private void requestPayOrder()
	{
		if (mStrOrderId != null)
		{
			LocalUserModel userModel = App.getApplication().getmLocalUser();
			if (userModel != null)
			{
				RequestModel model = new RequestModel();
				model.put("act", "pay_order");
				model.put("email", userModel.getUser_name());
				model.put("pwd", userModel.getUser_pwd());
				model.put("order_id", mStrOrderId);
				RequestCallBack<String> handler = new RequestCallBack<String>()
				{

					@Override
					public void onStart()
					{
						AppHelper.showLoadingDialog("请稍候...");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo)
					{
						Pay_orderActModel actModel = JsonUtil.json2Object(responseInfo.result, Pay_orderActModel.class);
						if (!SDInterfaceUtil.isActModelNull(actModel))
						{
							mPay_orderActModel = actModel;
							if (actModel.getResponse_code() == 1)
							{
								SDViewBinder.setTextView(mTvOrderSn, actModel.getOrder_sn());
								String payInfo = actModel.getPay_info();
								if (payInfo != null)
								{
									mTvPayInfo.setText(Html.fromHtml(payInfo));
								}

								int payStatus = SDTypeParseUtil.getIntFromString(actModel.getPay_status(), 0);
								if (payStatus == 1)// 订单已经付款
								{
									// TODO 弹出窗口提示已经付款下单成功
									showDoneOrderDialog(actModel.getPay_info());
									mBtnPay.setVisibility(View.GONE);
								} else
								{
									int showPayButton = SDTypeParseUtil.getIntFromString(actModel.getShow_pay_btn(), 0);
									if (SDViewBinder.setViewsVisibility(mBtnPay, showPayButton)) // 显示支付按钮
									{
										String payCode = actModel.getPay_code();
										String payMoneyFormat = actModel.getPay_money_format();
										if (!TextUtils.isEmpty(payCode) && !TextUtils.isEmpty(payMoneyFormat))
										{
											if (payCode.equals(PaymentType.MALIPAY)) // 支付宝/各银行
											{
												mBtnPay.setText(PaymentTypeString.MALIPAY + "(" + payMoneyFormat + ")");
											} else if (payCode.equals(PaymentType.WALIPAY)) // 支付宝
											{
												mBtnPay.setText(PaymentTypeString.WALIPAY + "(" + payMoneyFormat + ")");
											} else if (payCode.equals(PaymentType.WTENPAY)) // 财付通
											{
												mBtnPay.setText(PaymentTypeString.WTENPAY + "(" + payMoneyFormat + ")");
											}

											else if (payCode.equals(PaymentType.WXPAY)) // 微信支付
											{
												mBtnPay.setText(PaymentTypeString.WXPAY + "(" + payMoneyFormat + ")");
											}
										} else
										{

										}
									}
								}
								bindCouponlistData(actModel.getCouponlist());
							} else
							{

							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg)
					{

					}

					@Override
					public void onFinish()
					{
						AppHelper.hideLoadingDialog();
					}
				};
				InterfaceServer.getInstance().requestInterface(model, handler);
			}
		}
	}

	/**
	 * 绑定二维码
	 * 
	 * @param couponlist
	 */
	protected void bindCouponlistData(List<Pay_orderActCouponlistModel> couponlist)
	{
		if (couponlist != null && couponlist.size() > 0)
		{
			mLlScanCodes.setVisibility(View.VISIBLE);
			mLlScanCodes.removeAllViews();
			PayorderCodesAdapter adapter = new PayorderCodesAdapter(couponlist, PayActivity.this);
			for (int i = 0; i < adapter.getCount(); i++)
			{
				View view = adapter.getView(i, null, null);
				mLlScanCodes.addView(view);
			}
		} else
		{
			mLlScanCodes.setVisibility(View.GONE);
		}
	}

	private void showDoneOrderDialog(String content)
	{
		if (content != null)
		{
			new SDDialogConfirm().setTextContent(content).show();
		}
	}

	private void initIntentData()
	{
		mStrOrderId = getIntent().getStringExtra(EXTRA_ORDER_ID);
	}

	private void initTitle()
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				requestPayOrder();
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				// TODO 跳到订单列表
				Intent intent = new Intent(getApplicationContext(), MyOrderListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.putExtra(MyOrderListActivity.EXTRA_PAY_STATUS, 0);
				startActivity(intent);
				finish();
			}
		});

		mTitleSimple.setLeftImage(0);
		mTitleSimple.setLeftText("订单列表");

		mTitleSimple.setTitleTop("订单支付");

		mTitleSimple.setRightText("刷新");
	}

	private void registeClick()
	{
		mBtnPay.setOnClickListener(this);

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_pay_btn_pay:
			clickPay();
			break;

		default:
			break;
		}
	}

	private void clickPay() {
		if (mPay_orderActModel != null) {
			int isWap = SDTypeParseUtil.getIntFromString(mPay_orderActModel.getIs_wap(), -1);
			// wap支付
			if (isWap == 1) {
				String payUrl = mPay_orderActModel.getPay_wap();
				if (!TextUtils.isEmpty(payUrl)) {
					Intent intent = new Intent(App.getApplication(), WebViewActivity.class);
					intent.putExtra(WebViewActivity.EXTRA_URL, payUrl);
					startActivity(intent);

				} else {
					SDToast.showToast("wap支付链接为空");
				}

			} else {
				String payCode = mPay_orderActModel.getPay_code();
				if (payCode.equals(PaymentType.MALIPAY)) {
					payMalipayNew();

				} else if (payCode.equals(PaymentType.MCOD)) {
					showDoneOrderDialog(mPay_orderActModel.getPay_info());
				}

				// 微信支付
				else if (payCode.equals(PaymentType.WXPAY)) {
					payWxpay();
				}
			}

		}
	}

	// 微信支付主逻辑
	private void payWxpay() {
		if (mPay_orderActModel == null) {
			SDToast.showToast("Pay_orderActModel is null");
			return;
		}
		WxAppModel model = mPay_orderActModel.getWxapp();
		if (model == null) {
			SDToast.showToast("获取微信支付参数失败");
			return;
		}
		WxConfigModel wxConfigModel = model.getConfig();

		String appId = wxConfigModel.getAppid();
		if (TextUtils.isEmpty(appId))
		{
			SDToast.showToast("appId为空");
			return;
		}

		String partnerId = wxConfigModel.getPartnerid();
		if (TextUtils.isEmpty(partnerId))
		{
			SDToast.showToast("partnerId为空");
			return;
		}

		String prepayId = wxConfigModel.getPrepayid();
		if (TextUtils.isEmpty(prepayId))
		{
			SDToast.showToast("prepayId为空");
			return;
		}

		String nonceStr = wxConfigModel.getNoncestr();
		if (TextUtils.isEmpty(nonceStr))
		{
			SDToast.showToast("nonceStr为空");
			return;
		}

		String timeStamp = wxConfigModel.getTimestamp();
		if (TextUtils.isEmpty(timeStamp))
		{
			SDToast.showToast("timeStamp为空");
			return;
		}

		String packageValue = wxConfigModel.getPackagevalue();
		if (TextUtils.isEmpty(packageValue))
		{
			SDToast.showToast("packageValue为空");
			return;
		}

		String sign = wxConfigModel.getSign();
		if (TextUtils.isEmpty(sign))
		{
			SDToast.showToast("sign为空");
			return;
		}

		WXPayer.getInstance().setAppId(appId);

		PayReq req = new PayReq();
		req.appId = appId;
		req.partnerId = partnerId;
		req.prepayId = prepayId;
		req.nonceStr = nonceStr;
		req.timeStamp = timeStamp;
		req.packageValue = packageValue;
		req.sign = sign;

		WXPayer.getInstance().pay(req);
	}

	/**
	 * 支付宝SDK支付（新版）
	 * 
	 */
	private void payMalipayNew() {
		if (mPay_orderActModel == null) {
			return;
		}
		MalipayModel model = mPay_orderActModel.getMalipay();
		if (model == null) {
			SDToast.showToast("获取支付宝支付参数失败|");
			return;
		}

		MalipayConfigModel configModel = model.getConfig();
		if (configModel == null) {
			SDToast.showToast("MalipayConfigModel is null");
			return;
		}
		String orderSpec = configModel.getOrder_spec();
		String sign = configModel.getSign();
		String signType = configModel.getSign_type();

		if (TextUtils.isEmpty(orderSpec)) {
			SDToast.showToast("order_spec为空");
			return;
		}
		if (TextUtils.isEmpty(sign)) {
			SDToast.showToast("sign为空");
			return;
		}

		if (TextUtils.isEmpty(signType)) {
			SDToast.showToast("signType为空");
			return;
		}

		com.wenzhoujie.library.alipay.easy.SDAlipayer payer = new com.wenzhoujie.library.alipay.easy.SDAlipayer(this);
		payer.setmListener(new SDAlipayerListener() {

			@Override
			public void onStart() {

			}

			@Override
			public void onFinish(PayResult result) {
				String info = result.getMemo();
				String status = result.getResultStatus();
				if ("9000".equals(status)) {
					SDToast.showToast("支付成功");

				} else {
					if ("8000".equals(status)) {
						SDToast.showToast("支付结果确认中");

					} else {
						SDToast.showToast(info);
					}
				}
				requestPayOrder();
			}

			@Override
			public void onFailure(Exception e, String msg) {
				if (e != null) {
					SDToast.showToast("错误:" + e.toString());

				} else {
					if (!TextUtils.isEmpty(msg)) {
						SDToast.showToast(msg);
					}
				}

			}
		});
		payer.pay(orderSpec, sign, signType);
	}

	@Override
	protected void onResume() {
		requestPayOrder();
		super.onResume();
	}

	// private void requestCheckOrderStatus(String out_trade_no){
	// LocalUserModel user = App.getApplication().getmLocalUser();
	// if (user != null && out_trade_no != null)
	// {
	// RequestModel model = new RequestModel();
	// model.put("act", "check_order_status");
	// model.put("email", user.getUser_name());
	// model.put("pwd", user.getUser_pwd());
	// model.put("out_trade_no", out_trade_no);
	// RequestCallBack<String> handler = new RequestCallBack<String>()
	// {
	//
	// @Override
	// public void onStart()
	// {
	// AppHelper.showLoadingDialog("正在检查订单状态...");
	// }
	//
	// @Override
	// public void onSuccess(ResponseInfo<String> responseInfo)
	// {
	// System.out.println("requestCheckOrderStatus:" + responseInfo.result);
	// BaseActModel actModel = JsonUtil.json2Object(responseInfo.result,
	// BaseActModel.class);
	// if (!SDInterfaceUtil.isActModelNull(actModel))
	// {
	// if (actModel.getResponse_code() == 1)
	// {
	// // showDoneOrderDialog(actModel.getInfo());
	// requestPayOrder();
	// }
	// }
	// }
	//
	// @Override
	// public void onFailure(HttpException error, String msg)
	// {
	//
	// }
	//
	// @Override
	// public void onFinish()
	// {
	// AppHelper.hideLoadingDialog();
	// }
	// };
	// InterfaceServer.getInstance().requestInterface(model, handler);
	// }
	//
	// }

}